import { Render } from "./Render";
import { Webgl2DTextureSimple } from "./Webgl2DTextureSimple";

/*
 * @Author: Snow
 * @Date: 2021-09-12 10:00:00
 * @Description: 
 */
export class Webgl2DTexture2Image extends Webgl2DTextureSimple{
    private textures:WebGLTexture[] = [];
    private images:HTMLImageElement[] = [];


    private textrueInited:boolean = false;

    public override initUITools():void{
        //super.initUITools();
        this.createSlider("red",{value: 1, slide: this.onUpateSlide(this,"red"), min: 0, max: 1, step: 0.01, precision: 2})
        this.createSlider("green",{value: 0, slide: this.onUpateSlide(this,"green"), min: 0, max: 1, step: 0.01, precision: 2})
        this.createSlider("blue",{value: 0, slide: this.onUpateSlide(this,"blue"), min: 0, max: 1, step: 0.01, precision: 2})
        this.createSlider("alpha",{value: 1, slide: this.onUpateSlide(this,"alpha"), min: 0, max: 1, step: 0.01, precision: 2})
        this.uiParam = {red:1,green:0,blue:1,alpha:1};
        this.loadImage("./leaves.jpg");
        this.loadImage("./star.jpg");
    }

    public override initGLSL():void{
        this.vsSource = `
            attribute vec2 aPosition;
            attribute vec2 aTexCoord;

            uniform vec2 uResolution;
           
            varying vec2 vTexCoord;

            void main() {
                // 从像素坐标转换到 0.0 到 1.0
            vec2 zeroToOne = aPosition / uResolution;
        
            // 再把 0->1 转换 0->2
            vec2 zeroToTwo = zeroToOne * 2.0;
        
            // 把 0->2 转换到 -1->+1 (裁剪空间)
            vec2 clipSpace = zeroToTwo - 1.0;
        
            gl_Position = vec4(clipSpace * vec2(1,-1), 0, 1);
            vTexCoord = aTexCoord;
            }
        `;
        
        this.fsSource = `
            
            precision mediump float;
            // 纹理
            uniform sampler2D uImage0;
            uniform sampler2D uImage1;

            varying vec2 vTexCoord;

            void main() {
                vec4 color0 = texture2D(uImage0,vTexCoord);
                vec4 color1 = texture2D(uImage1,vTexCoord);
                gl_FragColor = color0 * color1;
            }
            `;
    }

    protected override loadImage(url:string):void{
        const gl = Render.GL;
        let image = new Image();
        image.src = url;  // MUST BE SAME DOMAIN!!!
        image.onload = () => {
           this.texImage = image;
           let tex = gl.createTexture();
           if(url == "./leaves.jpg"){
               this.textures[0] = tex;
               this.images[0] = image;
           }else{
                this.textures[1] = tex;
                this.images[1] = image;
           }
        };
    }

    public override draw():void{
        const gl = this.gl;
        gl.viewport(0,0,gl.canvas.width,gl.canvas.height);
        gl.clearColor(1,1,1,1);
        gl.clearDepth(1.0);
		gl.enable(gl.DEPTH_TEST);
		gl.depthFunc(gl.LEQUAL);
		gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        
        gl.useProgram(this.shaderProgram);

        const resolution:number[] = [
            gl.canvas.width,gl.canvas.height,
        ]
        gl.uniform2fv(this.uResolutionLoc,new Float32Array(resolution));

        const pos:number[] = [
            100.0,100.0,
            340.0,100.0,
            340.0,280.0,
            100.0,280.0,
        ];

        const posBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,posBuffer);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(pos),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(this.aPositionLoc);
        {
            gl.vertexAttribPointer(this.aPositionLoc,2,gl.FLOAT,false,0,0);
        }

        //纹理坐标
        const texPos:number[] = [
            0.0,0.0,
            1.0,0.0,
            1.0,1.0,
            0.0,1.0
        ];

        const texBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,texBuffer);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(texPos),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(this.aTexCoordLoc);
        {
            gl.vertexAttribPointer(this.aTexCoordLoc,2,gl.FLOAT,false,0,0);
        }

        // 创建纹理
        if(this.textures[0] && this.textures[1] && !this.textrueInited){
            this.textrueInited = true;
            for (let index = 0; index < 2; index++) {
                const tex = this.textures[index];
                gl.bindTexture(gl.TEXTURE_2D, tex);
                // 设置参数，让我们可以绘制任何尺寸的图像
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.images[index]);
            }
            
        }

        if(this.textrueInited){
            let uimage0:WebGLUniformLocation = gl.getUniformLocation(this.shaderProgram,"uImage0");
            //使用纹理
            gl.uniform1i(uimage0, 0);
            let uimage1:WebGLUniformLocation = gl.getUniformLocation(this.shaderProgram,"uImage1");
            //使用纹理
            gl.uniform1i(uimage1, 1);

            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D,this.textures[0]);
            gl.activeTexture(gl.TEXTURE1);
            gl.bindTexture(gl.TEXTURE_2D,this.textures[1]);
        }

        //顶点
        const indexs = [
            0,1,2,2,3,0
        ];

        const indexsBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indexsBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(indexs),gl.STATIC_DRAW);

        //gl.drawArrays(gl.TRIANGLES,0,6);
        gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0);
    }
}
